<template>
  <view class="address-panel">
    <!-- 关闭按钮 -->
    <text class="close icon-close" @tap="emit('close')"></text>
    <!-- 标题 -->
    <view class="title">配送至</view>
    <!-- 内容 -->
    <view class="content">
      <view class="item" v-for="(item, index) in addressList" :key="index">
        <view class="user">{{ item.receiver }} {{ item.contact }} </view>
        <view class="address">{{ item.fullLocation }} {{ item.address }}</view>
        <text
          :class="item.selected ? 'icon icon-checked' : 'icon icon-ring'"
          @tap="onTap(item)"
        ></text>
      </view>
    </view>
    <view class="footer">
      <navigator class="button primary" url="/pagesMember/address-form/address-form">
        新建地址
      </navigator>
      <view v-if="false" class="button primary">确定</view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { onReady, onShow } from '@dcloudio/uni-app'
import Api from '@/services'
import type { TAddressResult } from '@/types/address'
import { ref } from 'vue'
import { useAddressStore } from '@/stores/modules/address'
import _ from 'lodash'

const addressStore = useAddressStore()
type TAddressItem = TAddressResult & {
  selected?: boolean
}

const emit = defineEmits<{
  (event: 'close'): void
}>()
const addressList = ref<TAddressItem[]>()

const getAddressList = async () => {
  const res = await Api.LoginAPI.getAddressList()
  addressList.value = res.result
}

onReady(() => {
  getAddressList()
})

onShow(() => {
  getAddressList()
})

const onTap = (item: TAddressItem) => {
  if (item.selected) {
    // 原item已选择，取消选择
    item.selected = false
  } else {
    // 原item未选择，选择
    const oldAddress = addressList.value?.find((address) => address.selected)
    oldAddress?.selected && (oldAddress.selected = false)
    item.selected = true
    addressStore.changeSelectedAddress(_.omit(item, 'selected'))
  }
}
</script>

<style lang="scss" scoped>
@import '../styles/AddressPanel.scss';
</style>
